﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WarehouseManagement.DataAccess;

namespace WarehouseManagement.BusinessLogic.BC
{
    public static class BCExtensions
    {

        //public static BoughtMerchandiseDebit GetDebit(this BaseBC bc, int supplierId, DateTime untilDate)
        //{
        //    var list = bc.Context.BoughtMerchandiseDebits.Where(e => (e.SupplierId == supplierId)
        //       && (e.FromDate.Date <= untilDate.Date))
        //       .OrderByDescending(e => e.FromDate)
        //       .ToList();

        //    if (list == null || list.Count == 0)
        //    {
        //        return null;
        //    }

        //    var item = list.FirstOrDefault();
        //    return item;
        //}
        // Get tiền đã thu

        //public static DateTime? GetDateOfLastPeriodDebt(this BaseBC bc, string documentNumber)
        //{
        //    var obj = bc.Context.BoughtMerchandiseDebits.SingleOrDefault(e => e.DocumentNumber == documentNumber);
        //    if (obj != null)
        //        return obj.FromDate;
        //    return null;
        //}
        private static int? GetSupplierIdByDocumentNumber(this BaseBC bc, string documentNumber)
        {
            var obj = bc.Context.BoughtMerchandiseDebits.FirstOrDefault(e => e.DocumentNumber == documentNumber);
            if (obj == null) return null;
            return obj.SupplierId;
        }
        public static decimal GetReceiptsValueOf(this BaseBC bc, string documentNumber, DateTime fromDate, DateTime toDate, DateTime debtDate)
        {

            var list = bc.Context.Receipts.Where(e => e.DocumentNumber == documentNumber
                && (e.CreatedDate >= fromDate && e.CreatedDate.Date <= toDate.Date))
                .AsEnumerable();

            //var debits = bc.Context.BoughtMerchandiseDebits.Where(e => e.DocumentNumber == documentNumber
            //    && (e.FromDate >= fromDate && e.FromDate <= toDate))
            //    .OrderByDescending(e => e.FromDate)
            //    .ToList();

            //BoughtMerchandiseDebit debitObj = null;

            //if (debits.Count() > 0)
            //{
            //    debitObj = debits.FirstOrDefault();
            //}

            //var debtDate = GetDateOfLastPeriodDebt(bc, documentNumber);

            list = list.Where(e => e.CreatedDate >= debtDate).ToList();



            if (list.Count() > 0)
                return list.Sum(e => e.Value);
            return 0;
        }
    }
}
